package com.zzptc.zzsgz.bdsjws.utils;

import android.app.NotificationManager;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.support.v4.app.NotificationCompat;

import com.zzptc.zzsgz.bdsjws.MyApplication;
import com.zzptc.zzsgz.bdsjws.R;
import com.zzptc.zzsgz.bdsjws.com.Constants;
import com.zzptc.zzsgz.bdsjws.db.MobileInfoDao;
import com.zzptc.zzsgz.bdsjws.vo.Contact;
import com.zzptc.zzsgz.bdsjws.vo.MobileInfo;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static android.R.attr.name;
import static android.R.attr.soundEffectsEnabled;

/**
 * Created by Administrator on 2017/4/23.
 */

public class MyUtil {
    public static SharedPreferences getSharedPre(){
        return MyApplication.getContext().getSharedPreferences("loginnew", Context.MODE_PRIVATE);
    }
    public static boolean isSD() {
        boolean flag=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (flag) {
            return true;
        }
        return false;
    }
    public static File getDir(){
        if (isSD()){
            return Environment.getExternalStorageDirectory();
        }
        return Environment.getDownloadCacheDirectory();
        //return Environment.getExternalStorageDirectory();
    }
    public static Intent getInstallIntent(File file){
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        return intent;
    }
    public static int daysBetween(Date smdate, Date bdate) throws ParseException
    {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }
    public static int getVersionCode(Context context)//获取版本号(内部识别号)
    {
        try {
            PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }
    //复制文件到手机
    public static void copyFileToMobile(Context context, String s, String dbname) throws IOException {
        //MyApplication.getContext().getPackageName();
        //原始文件的位置
        URL url=context.getClass().getClassLoader().getResource("assets/"+dbname);
                //文件的路径
        String dbfiledir="data/data/"+MyApplication.getContext().getPackageName()+"/databases";
        File fileMobiledir=new File(dbfiledir);
        if (!fileMobiledir.exists()){
            fileMobiledir.mkdir();
        }
        File dbfileNobile=new File(fileMobiledir+"/"+dbname);
        if (dbfileNobile.exists()){
            dbfileNobile.createNewFile();
        }
        //第一个参数 是路径源文件  第二个参数  目的地包含路径的文件
        FileUtils.copyURLToFile(url,dbfileNobile);

    }

    //得到手机是的联系人信息
    //姓名 电话号码 手机归属地 三个属性封装成一个实体类
   public static List<Contact> getAllContacts(){
       List<Contact> lists=new ArrayList<Contact>();
       //通过内容提供者查询
       ContentResolver contentResolver=MyApplication.getContext().getContentResolver();
       Cursor cursor=contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);
       if (cursor==null){

       }else {
           while (cursor.moveToNext()) {

               //获取ID

               int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
               //联系人的姓名
               String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
               int num=cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
              String phonenum=null;
               //如果大于0，表示有电话号码
               if (num>0){
                   phonenum=getPhonenumByID(id);
               }
               //获取手机归属地
               String addr=null;
               addr=getAddressByTel(phonenum);



               Contact contact=new Contact(id,name,phonenum,addr);
               lists.add(contact);
           }
           cursor.close();
       }
       return lists;
   }
    //正则表达式
    public static String getAddressByTel(String tel){
        String address=null;
        //MobileInfo mobileInfo=null;
       // String[] aa=tel.split(" ");
        String newtel=tel.replace(" ","").replace("-","");
        String telnum=null;
        if (newtel.length()==11&&newtel.matches("^1[3578]\\d{9}$")){
            //手机号码
            telnum=newtel.substring(0,7);
            address=getMobileAddrByTel(telnum);
            System.out.println(address);
        }else {
            //座机号码？3+7 3+8 4+7 4+8
            int length=newtel.length();
            switch (length){
                case 10:
                    getZUOJIAddrByTel(newtel,3);
                    break;
                case 11:
                    address=getZUOJIAddrByTel(newtel,3);
                    if (address==null){
                        address=getZUOJIAddrByTel(newtel,4);
                    }
                    break;
                case 12:
                    address=getZUOJIAddrByTel(newtel,4);
                    break;
                default:
                    address="未知";
            }

        }

      /*  MobileInfo mobileInfo= MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(telnum)).distinct().unique();
*/
        return address;
    }
    public static String getZUOJIAddrByTel(String tel,int length){
     MobileInfo   mobileInfo=MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.AreaCode.eq(tel.substring(0,length))).limit(1).distinct().unique();
        return mobileInfo.getMobileArea();
    }
    public static String getMobileAddrByTel(String tel){
        MobileInfo   mobileInfo=MyApplication.getMobileSession().getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(tel)).limit(1).distinct().unique();
        return mobileInfo.getMobileArea();
    }

    public static String getPhonenumByID(int id){
        String telnum=null;
        ContentResolver contentResolver=MyApplication.getContext().getContentResolver();
       Cursor cursor= contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}
               ,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?",new String[]{id+""},null);
        if (cursor!=null){
            //我这只取一个电话号码
            if (cursor.moveToNext()){
                telnum=cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
        }
        cursor.close();
        return telnum;
    }


}
